package cloud.maque.auth.service;


import cloud.maque.auth.annotations.LoginTypeAnn;
import cloud.maque.auth.entity.AuthUser;
import cloud.maque.auth.exceptions.UserDisabledException;
import cloud.maque.auth.exceptions.UserInfoException;
import cloud.maque.auth.exceptions.UserNotExistsException;
import cloud.maque.auth.exceptions.UserPasswordErrorException;
import cloud.maque.auth.model.LoginRequest;
import cloud.maque.auth.model.LoginResponse;
import cloud.maque.common.core.enums.LoginType;
import cloud.maque.common.core.utils.UserPasswordUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户名，密码登录
 */
@Service
@LoginTypeAnn(LoginType.PASSWORD)
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    UserService userService;

    @Override
    public LoginResponse login(LoginRequest request) {


        if (StrUtil.isEmptyIfStr(request.getUserName()) || StrUtil.isEmptyIfStr(request.getPassWord())) {
            throw new UserInfoException();
        }

        AuthUser user = userService.getUserByUserName(request.getUserName());
        if (user == null) {
            throw new UserNotExistsException();
        }
        if (!StrUtil.isEmptyIfStr(user.getDisabled()) && user.getDisabled().equals(1)) {
            throw new UserDisabledException();
        }

        //验证密码
        if (!UserPasswordUtil.verify(request.getPassWord(), user.getPassWord(), user.getUserName())) {
            throw new UserPasswordErrorException();
        }

        LoginResponse loginResponse = new LoginResponse();
        BeanUtil.copyProperties(user, loginResponse);
        return loginResponse;
    }
}
